package ac.aiit.tw;

import java.io.IOException;
import java.util.ArrayList;

import ac.aiit.tw.serialCommand.ICommMessageListener;
import ac.aiit.tw.serialCommand.serialCommException;

public class serialCommand_synchronized implements ICommMessageListener {
	private serialCommand _comm = null;
	private boolean _inflight = false;
	private ArrayList<ICommMessageListener> _listeners = new ArrayList<ICommMessageListener>();
	private serialCommand_synchronized(serialCommand comm){
		super();
		this._comm = comm;
		this._comm.addMesageListener(this);
	}
	public static final serialCommand_synchronized getInstance(String id) throws serialCommException{
		serialCommand_synchronized ret = new serialCommand_synchronized(serialCommand.getInstance(id));
		return ret;
	}
	public synchronized boolean write(Object msg) throws IOException{
		if(!this._inflight){
			this._inflight = true;
			if(msg instanceof String){
				this._comm.write((String)msg);
			}else if (msg instanceof Integer){
				this._comm.write(((Integer)msg).intValue());
			}else{
				throw new IOException(String.format("Unsupported type %s", msg.getClass().getName()));
			}
			return true;
		}else{
			return false;
		}
	}
	public boolean addMessageListener(ICommMessageListener listener){
		return this._listeners.add(listener);
	}
	private void clearMessageListener(){
		this._listeners.clear();
	}
	@Override
	public void onMessage(String text) throws serialCommException {
		this._inflight = false;
		for(ICommMessageListener listener : this._listeners){
			listener.onMessage(text);
		}
	}

}
